from spyne import Application, rpc, ServiceBase, String, Unicode
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
# 将Spyne创建的app 发布为django
from spyne.server.django import DjangoApplication
from django.views.decorators.csrf import csrf_exempt
from config.redis_conf import r
from database.db import db
from suds.client import Client
from config.url_conf import fs_url
import logging, json

# Create your views here.

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')


class Repay(ServiceBase):
    global result

    # 正常月还
    @rpc(String, _returns=Unicode)  # rpc内包含了传入参数以及传出参数的类型,_returns=String是传出参数
    def repayFund(self, params):
        logging.info('恒易融正常月还，接收参数params{0}'.format(params))
        if r.get("is_hyr_status") == '1':
            client = Client(url=fs_url)
            result = client.service.repayFund(params)
        else:
            borrowid = str(json.loads(params)["borrowid"])
            data = {}
            if not borrowid:
                result = '合同id不能为空'
            elif borrowid in r.hkeys('fund_fail_list'):  # 取fail_list对应的hash中所有的key的值
                # r.hget('fail_list',borrowid)获取name为fail_list，key为borrowid的value
                result = 'msg:提交的合同id：%s有误' % (borrowid)
            elif borrowid in r.hkeys('fund_success_list'):
                result = '{"msg":"failure","data":"pt-合同已还款提交成功!","status":11}'
            else:
                r.hset('fund_success_list', borrowid, 1)
                result = '{"msg":"success","data":"还款提交成功","status":1}'
                rs = db.query_repay_plan(borrowid=borrowid, tablename='repay_plan')
                data["cid"] = borrowid
                data["status"] = 1
                data["reason"] = '还款成功'
                data["repaytime"], data["repaymoney"], data["principal"], data["interest"], data["fq_money"], data["term"], \
                data["contnum"] = rs
                logging.info('恒易融正常月还回调需要的参数：{0}'.format(data))
                r.hset('repayFund_list', borrowid, data)
        return result

    # 逾期划扣
    @rpc(String, _returns=Unicode)
    def repayOverdue(self, params):
        logging.info('恒易融逾期划扣接收参数params{0}'.format(params))
        if r.get("is_hyr_status") == '1':
            client = Client(url=fs_url)
            result = client.service.repayOverdue(params)
        else:
            collection_id = json.loads(params)['collection_id']
            borrowid = str(json.loads(params)['borrowid'])
            is_already = json.loads(params)['is_already']
            repay_money = json.loads(params)['repay_money']
            is_normal = json.load(params)['is_normal']
            detail = json.loads(params)['detail']
            write_off_money = json.loads(params)['write_off_money']
            write_off_detail = json.loads(params)['write_off_detail']
            orderno_id = json.load(params)['orderno_id']
            data = {}
            if (not collection_id) or (not borrowid) or (is_already == '') or (repay_money == '') or (detail == ''):
                result = '必填参数缺失'
            elif borrowid in r.hkeys('overdue_fail_list'):
                # result = overdue_dict[r.hget('overdue_fail_list', borrowid)]
                result = 'msg:提交的合同id：%s有误' % (borrowid)
            elif borrowid in r.hkeys('overdue_success_list'):
                result = '{"msg": "failure", "data": "pt-逾期记录已存在", "status": 3}'
            else:
                if write_off_money > 0:
                    if not write_off_detail:
                        result = '必填参数缺失'
                    else:
                        r.hset('overdue_success_list', borrowid, 1)
                        result = '{"msg": "success", "data": {"id": %s}, "status": 1}' % (borrowid)
                else:
                    r.hset('overdue_success_list', borrowid, 1)
                    result = '{"msg": "success", "data": {"id": %s}, "status": 1}' % (borrowid)
                    data["collection_id"] = collection_id
                    data["is_already"] = is_already
                    data["status"] = 1
                    data["orderno_id"] = orderno_id
                    data["account_id"] = borrowid
                    data["term"] = '1'
                    data["repay_money"] = repay_money
                    data["success_money"] = repay_money
                    data["is_normal"] = is_normal
                    r.hset('repayOverdue_list', borrowid, data)
        return result

    # 结清和划回
    @rpc(String, _returns=Unicode)
    def addSettleData(self, params):
        logging.info('恒易融结清接收参数params{0}'.format(params))
        if r.get("is_hyr_status") == '1':
            client = Client(url=fs_url)
            result = client.service.addSettleData(params)
        else:
            rew_data = json.loads(params)
            data = {}
            if rew_data.__contains__('settle_type'):  # 提前结清
                settle_type = rew_data['settle_type']
                contnum = rew_data['contnum']
                repay_money = rew_data['repay_money']
                if (settle_type == None) or (contnum == "") or (repay_money == None):
                    result = '必填参数缺失'
                elif contnum in r.hkeys('settle_fail_list'):
                    result = '合同不可提交'
                elif contnum in r.hkeys('settle_success_list'):
                    result = '{"msg":"failure","status":8,"data":"pt-该合同已经存在结清任务!"}'
                else:
                    r.hset('settle_success_list', contnum, 1)
                    data["account_number"] = contnum
                    data["real_money"] = repay_money
                    data["status"] = 1
                    data["type"] = 2
                    r.hset('addSettleData_list', contnum, data)
                    result = '{"msg":"success","status":1,"data":"pt-该合同结清任务提报成功!"}'
            else:  # 紧急划回
                earlyType = rew_data['earlyType']
                accountNumber = rew_data['accountNumber']
                isPaid = rew_data['isPaid']
                loanMoney = rew_data['loanMoney']
                diffWorkDay = rew_data['diffWorkDay']
                totalLiXi = rew_data['totalLiXi']
                urgent_back_cost = rew_data['urgent_back_cost']
                earlyMoney = rew_data['earlyMoney']
                back_money = rew_data['back_money']
                if (earlyType == None) or (accountNumber == "") or (isPaid == None) or (loanMoney == None) or (
                        diffWorkDay == None) or (
                        totalLiXi == None) or (urgent_back_cost == None) or (earlyMoney == None) or (back_money == None):
                    result = '必填参数缺失'
                elif accountNumber in r.hkeys('settle_fail_list'):
                    result = '合同不可提交'
                elif accountNumber in r.hkeys('settle_success_list'):
                    result = '{"msg":"failure","status":8,"data":"pt-该合同已经存在结清任务!"}'
                else:
                    r.hset('settle_success_list', accountNumber, 1)
                    data["account_number"] = accountNumber
                    data["real_money"] = earlyMoney
                    data["status"] = "1"
                    data["type"] = "2"
                    r.hset('addSettleData_list', accountNumber, data)
                    result = '{"msg":"success","status":1,"data":"pt-该合同结清任务提报成功!"}'
        return result


# 命名空间 tns 传入类型Soap11() 传出类型Soap11()
application = Application([Repay], tns='spyne.repay.soap', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())

# 定义DjangoApplication
item_app = csrf_exempt(DjangoApplication(application))

# if __name__ == '__main__':
#     import logging
#     from wsgiref.simple_server import make_server
#
#     # Wrap the Spyne application with its wsgi wrapper
#     wsgi_app = WsgiApplication(application)
#
#     logging.basicConfig(level=logging.DEBUG)
#     logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
#     logging.info("listening to http://127.0.0.1:8000")
#     logging.info("wsdl is at: http://localhost:8000/WebApi?wsdl")
#     server = make_server('127.0.0.1', 8000, wsgi_app)
#     server.serve_forever()
